package com.starbaba.buriedPoint.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.starbaba.base.dao.LoanManagerBaseDao;
import com.starbaba.base.service.RegisterRecommendActivityService;
import com.starbaba.base.service.impl.RegisterRecommendActivityServiceImpl;
import com.starbaba.buriedPoint.service.CommonActivityRegisterDisplayService;
import com.tuanzi.server.loan_base.model.db.Common_Activity_Register_Record;

public class CommonActivityRegisterDisplayServiceImpl extends LoanManagerBaseDao implements CommonActivityRegisterDisplayService{
	
	private RegisterRecommendActivityService activityService;
	
	public CommonActivityRegisterDisplayServiceImpl(){
		this.activityService = new RegisterRecommendActivityServiceImpl();
	}

	@Override
	public List<Common_Activity_Register_Record> getList(
			Map<String, Object> paramsMap, int pageNo, int pageSize) {
		
		String sql = generateGetListSql(paramsMap) + " ORDER BY ctime DESC LIMIT ?,? ";
		List<Common_Activity_Register_Record> list = new ArrayList<Common_Activity_Register_Record>();
		
		try {
			
			list = getDao().list(sql, Common_Activity_Register_Record.class, pageNo, pageSize);
			
			//根据活动类型回显活动名称
			Map<String, String> activityMap = activityService.getRegisterRecommendActivityMap();
			for(Common_Activity_Register_Record record: list){
				
				String activityType = record.getActivity_type();
				record.setActivity_type(activityMap.get(activityType));
				
			}
			
			
		} catch (AppException e) {
			LogService.error(e);
		}
		
		return list;
	}

	@Override
	public int countList(Map<String, Object> paramsMap) {
		
		String sql = "SELECT COUNT(*) FROM (" +  generateGetListSql(paramsMap) + ") AS a";
		int result = 0;
		
		try {
			result = getDao().getInt(sql);
		} catch (AppException e) {
			LogService.error(e);
		}		
		return result;
	}
	
	private String generateGetListSql(Map<String, Object> paramsMap){
		
		String startDate = (String) paramsMap.get("startDate");
		String endDate = (String) paramsMap.get("endDate");
		String phone = (String) paramsMap.get("phone");
		String channel = (String) paramsMap.get("channel");
		
		StringBuilder sql = new StringBuilder("SELECT * FROM `common_activity_register_record` WHERE 1= 1 ");
		
		if(StringUtils.isNotEmpty(startDate)){
			sql.append(" AND cdate >= '" + startDate + "'");
		}
		
		if(StringUtils.isNotEmpty(endDate)){
			sql.append(" AND cdate <= '" + endDate + "'");
		}
		
		if(StringUtils.isNotEmpty(phone)){
			sql.append(" AND phone = '" + phone + "'");
		}
		
		if(StringUtils.isNotEmpty(channel)){
			sql.append(" AND channel = '" + channel + "'");
		}
		
		return sql.toString();
		
	}

}
